package com.mic.config;

import com.mic.handle.AuthenticationEntryPointImpl;
import com.mic.util.RSAUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        // userInfo接口需要SCOPE_profile权限
                        .requestMatchers("/userInfo").hasAuthority("SCOPE_message.read")
                        // 其它访问都需要鉴权
                        .anyRequest().authenticated()
                )
                // 资源服务器默认配置
                .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt
                        // 配置set-uri替换yaml的jwk-set-uri配置
//                        .jwkSetUri("")
                        // 配置自己的decoder，替换从远程获取的公钥
                        .decoder(jwtDecoder())
                ).authenticationEntryPoint(new AuthenticationEntryPointImpl()));
        return http.build();
    }

    /**
     * 自定义JwtDecoder
     */
    public JwtDecoder jwtDecoder() {
        NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(RSAUtil.getPublicKey()).build();
//        OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
//                new JwtTimestampValidator(Duration.ofSeconds(60)),
//                new JwtIssuerValidator(issuerUri));
//        jwtDecoder.setJwtValidator(withClockSkew);
        return jwtDecoder;
    }


}
